package com.sunlands.qdcy.deskmate.web;

import com.alibaba.fastjson.JSON;
import com.sunlands.qdcy.deskmate.common.annotation.AutoLog;
import com.sunlands.qdcy.deskmate.constant.CommonResultMessage;
import com.sunlands.qdcy.deskmate.dao.pojo.PaymentWechatNoticeRecord;
import com.sunlands.qdcy.deskmate.enums.PayStatus;
import com.sunlands.qdcy.deskmate.service.PostgraduateWechatPayService;
import com.sunlands.qdcy.deskmate.util.PayUtils;
import com.sunlands.qdcy.deskmate.util.RequestUtil;
import com.sunlands.qdcy.deskmate.util.ResponseUtil;
import com.sunlands.qdcy.deskmate.util.StringUtil;
import com.sunlands.qdcy.deskmate.vo.BusinessResult;
import com.sunlands.qdcy.deskmate.vo.Order;
import com.sunlands.qdcy.deskmate.vo.WechatCreateOrderVO;
import com.sunlands.qdcy.deskmate.vo.feign.VipSetMealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zl
 * @version 1.0
 * @date Created in 2020/4/11
 */
@Slf4j
@RestController
@RequestMapping("/pay/wechat/postgraduate")
@Api(tags = {"考研自习室-微信支付相关接口"})
public class PostgraduateWechatPayController extends BaseController{

    @Autowired
    private PostgraduateWechatPayService postgraduateWechatPayService;


    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/create-order")
    @ApiOperation(value = "APP调用-微信支付下单接口,只传 goodsNumber即可", response = WechatCreateOrderVO.class)
    public BusinessResult<WechatCreateOrderVO> createOrder(HttpServletRequest request,@RequestBody Order order) throws Exception {
        //校验信息
        Asserts.notNull(order.getGoodsNumber(), "商品编号不能为空！");
        order.setUserId(currentUserId());
        //调用vip服务获取商品信息，校验商品编号
        VipSetMealVO setMeal = userCenterService.getVipSetMeal(order.getGoodsNumber()).getData();
        Asserts.notNull(setMeal, "没有查询到对应的商品信息！id = " + order.getGoodsNumber());

        order.setTotalAmount(setMeal.getPrice());
        order.setSubject(setMeal.getName());
        order.setBody(setMeal.getContent());
        order.setSpbillIp(RequestUtil.getNewRemoteAddr(request));


        WechatCreateOrderVO createOrderVO = postgraduateWechatPayService.createOrder(order);

        if (Objects.nonNull(createOrderVO)) {
            log.info("微信支付下单成功 createOrderVO = {}", JSON.toJSONString(createOrderVO));
            return BusinessResult.createSuccessInstance(createOrderVO);
        } else {
            log.error("微信支付下单失败 userId={},outTradeNo={}",order.getUserId(),order.getOutTradeNo());
            return BusinessResult.createInstance(CommonResultMessage.FAIL.code, "微信支付下单失败");
        }
    }

    @AutoLog
    @PostMapping(value = "/receivePayBack")
    @ResponseBody
    public void receivePayBack(HttpServletResponse response, @RequestBody String body) throws Exception {
        log.info("微信支付回调，body ={}", body);
        Map remap = new HashMap();
        try {
            if (StringUtil.notEmpty(body)) {
                remap = postgraduateWechatPayService.payNotice(body);
            } else {//返回内容为空
                remap.put("return_code", PayStatus.failed.getCode());
                remap.put("return_msg", "返回内容为空");
                log.error("微信支付回调， 返回内容为空");
            }

        } catch (Exception e) {
            log.error("微信支付回调 异常 ，body ={}",body, e);
            remap.put("return_code", PayStatus.failed.getCode());
            remap.put("return_msg", "接收异常");
        }
        String xml = PayUtils.map2Xml(remap);
        ResponseUtil.sendMessageNoCache(response, xml, ResponseUtil.CONTENT_TYPE_XML);
    }


    @AutoLog
    @ApiOperation(value = "工具-微信订单状态查询", response = BusinessResult.class)
    @GetMapping("/query")
    public BusinessResult<PaymentWechatNoticeRecord> query(@RequestParam String outTradeNo) throws Exception {
        return BusinessResult.createSuccessInstance(postgraduateWechatPayService.pullOrderStatus(outTradeNo));
    }




}
